﻿




using System;
using Hotpot.Infrastructure;
using Hotpot.Models;
using Hotpot.Modules.FormsAuthentication.Extensions;
using Hotpot.Modules.FormsAuthentication.Models;
using Hotpot.Modules.Membership.Repositories;
using Hotpot.Plugins.Extensions;
using Hotpot.Validation;

namespace Hotpot.Modules.FormsAuthentication.Services
{
    public class FormsAuthenticationUserService : IFormsAuthenticationUserService
    {
        private readonly IUserRepository repository;
        private readonly IValidationService validator;
        private readonly IPluginEngine pluginEngine;
        private readonly HotpotContext context;

        public FormsAuthenticationUserService(IUserRepository repository, IValidationService validator, IPluginEngine pluginEngine, HotpotContext context)
        {
            this.repository = repository;
            this.validator = validator;
            this.pluginEngine = pluginEngine;
            this.context = context;
        }

        #region IFormsAuthenticationUserService Members

        public ModelResult ChangePassword(User user, UserChangePasswordInput userInput)
        {
            ValidationStateDictionary validationState = new ValidationStateDictionary();

            validationState.Add(typeof(UserChangePasswordInput), validator.Validate(userInput));

            if (!validationState.IsValid) return new ModelResult(validationState);

            string passwordSalt = Guid.NewGuid().ToString("N");
            string password = userInput.Password.SaltAndHash(passwordSalt);

            repository.SetModuleData(user, "FormsAuthentication", string.Format("{0}|{1}", passwordSalt, password));

            pluginEngine.ExecuteAll("UserChangePassword", new { user, context });

            return new ModelResult();
        }

        #endregion
    }
}
